﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Business
{
    public partial class frm_Add_PartMistake : Form
    {
        public frm_Add_PartMistake()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            getOrderNo();
            this.orderNo.Properties.AutoComplete = true;
        }

        ///////////////////////////////////
        /// Load Order No
        ///////////////////////////////////
        private void getOrderNo()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT OrderNo, POID FROM [241_PartReceive] WHERE Quantity>0 ORDER BY OrderNo, POID";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();                
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["OrderNo"].ToString();
                    item.Value = dataReader["OrderNo"].ToString();
                    this.orderNo.Properties.Items.Add(item);

                    ComboboxItem item2 = new ComboboxItem();
                    item2.Text = dataReader["POID"].ToString();
                    item2.Value = dataReader["POID"].ToString();
                    this.poID.Properties.Items.Add(item2);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get OrderNo list");
            }
        }

        private void orderNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.poID.SelectedIndex = this.orderNo.SelectedIndex;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            bool pass = true;
            string error = null;
            ComboboxItem ordernoItem = (ComboboxItem)orderNo.SelectedItem;
            ComboboxItem poidItem = (ComboboxItem)poID.SelectedItem;
            int ngQty = 0;
            int spQty = 0;

            int quantityPODetails = sumQuantityPODetails(ordernoItem.Value.ToString(), poidItem.Value.ToString());
            int quantityPartReceive = sumQuantityPartReceive(ordernoItem.Value.ToString(), poidItem.Value.ToString());
            int quantityPOMistake = sumQuantityPOMistake(ordernoItem.Value.ToString(), poidItem.Value.ToString());
            int quantityPOMistakeReturn = sumQuantityPOMistakeReturn(ordernoItem.Value.ToString(), poidItem.Value.ToString());

            /// Check input Date
            if (pass)
            {
                if (string.IsNullOrEmpty(inputDate.DateTime.Date.ToString().Trim()))
                {
                    pass = false;
                    error = "Please select Input Date";
                }
            }

            /// Check OrderNo selection
            if (pass)
            {
                if (string.IsNullOrEmpty(ordernoItem.Value.ToString().Trim()))
                {
                    pass = false;
                    error = "Please select OrderNo";
                }
            }
            
            /// Check quantity of Part received
            if (pass)
            {
                if (quantityPartReceive == 0)
                {
                    pass = false;
                    error = "There is no Part received for OrderNo " + ordernoItem.Value.ToString();
                }
            }

            /// Check info sheet No.
            if (pass)
            {
                if (string.IsNullOrEmpty(infoSheet.Text.Trim()))
                {
                    pass = false;
                    error = "Plase enter mistake sheet No.";
                }
            }

            /// Check NG Quantity input
            if (pass)
            {
                if (string.IsNullOrEmpty(ngQuantity.Text.Trim()))
                {
                    pass = false;
                    error = "Please enter a valid NG Quantity";
                }
                else
                {
                    ngQty = Int32.Parse(ngQuantity.Text.Trim());
                }
            }

            /// Check sum ngQty + spQty
            if (!string.IsNullOrEmpty(spQuantity.Text.Trim()))
            {
                spQty = Int32.Parse(spQuantity.Text.Trim());
            }
            int ngspQty = ngQty + spQty;
            int remain = quantityPartReceive + quantityPOMistakeReturn - quantityPOMistake;
            if (pass)
            {
                if (ngspQty <= 0)
                {
                    pass = false;
                    error = "NG Quantity + SP Quantity must be greater than 0";
                }
            }

            if (pass)
            {
                if (ngspQty > remain)
                {
                    pass = false;
                    error = "RRC have only " + remain + " units. Please check input quantity";
                }
            }

            if (pass)
            {
                if (ngspQty > quantityPODetails)
                {
                    pass = false;
                    error = "The OrderNo " + ordernoItem.Value.ToString() + " has only " + quantityPODetails + " units. Please check input quantity";
                }
            }

            if (pass)
            {
                if (string.IsNullOrEmpty(mistakeContent.Text.Trim()))
                {
                    pass = false;
                    error = "Please enter mistake content";
                }
            }
            if (pass)
            {
                DateTime inputdate;
                DateTime.TryParse(inputDate.DateTime.Date.ToString(), out inputdate);

                try
                {
                    myConnection.Open();
                    string sql = "INSERT INTO [241_POMistake] (InputDate, POID, OrderNo, Quantity,"
                        + " SPQuantity, MistakeContent, InforNo)"
                        + " VALUES (@inputdate, '" + poidItem.Value.ToString() + "', '" + ordernoItem.Value.ToString() + "',"
                        + " " + ngQty + ", " + spQty + ", '" + mistakeContent.Text + "', '" + infoSheet.Text + "')";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@inputdate", SqlDbType.DateTime).Value = inputdate.Date;
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("Part Mistake added success.");
                    clearForm();
                }
                catch (Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show(ex.Message);
                    //MessageBox.Show("Cannot add Part Mistake. Please try again.");
                }
            }
            else
            {
                MessageBox.Show(error);
            }
        }

        ////////////////////////////////////////////
        /// Sum quantity from PODetails
        ////////////////////////////////////////////        
        private int sumQuantityPODetails(string orderno, string poid)
        {
            int ret = 0;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT SUM(Quantity) FROM [241_PODetails]"
                    + " WHERE POID='" + poid + "' AND OrderNo='" + orderno + "' AND Cancelled=0 AND Change=0";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    if (!string.IsNullOrEmpty(dataReader[0].ToString()))
                    {
                        ret = Int32.Parse(dataReader[0].ToString());
                    }
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get sum quantity from PODetails for OrderNo " + orderno + " of POID " + poid);
            }
            return ret;
        }

        ////////////////////////////////////////////////////////
        /// Sum quantity from PartReceive
        ////////////////////////////////////////////////////////
        private int sumQuantityPartReceive(string orderno, string poid)
        {
            int ret = 0;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT SUM(Quantity) FROM [241_PartReceive]"
                    + " WHERE POID='" + poid + "' AND OrderNo='" + orderno + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    if (!string.IsNullOrEmpty(dataReader[0].ToString()))
                    {
                        ret = Int32.Parse(dataReader[0].ToString());
                    }
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get sum quantity from PartReceive for OrderNo " + orderno + " of POID " + poid);
            }
            return ret;
        }

        ////////////////////////////////////////////////////////
        /// Sum quantity from POMistake
        ////////////////////////////////////////////////////////
        private int sumQuantityPOMistake(string orderno, string poid)
        {
            int ret = 0;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT SUM(Quantity) FROM [241_POMistake]"
                    + " WHERE POID='" + poid + "' AND OrderNo='" + orderno + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    if (!string.IsNullOrEmpty(dataReader[0].ToString()))
                    {
                        ret = Int32.Parse(dataReader[0].ToString());
                    }
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get sum quantity from POMistake for OrderNo " + orderno + " of POID " + poid);
            }
            return ret;
        }

        ////////////////////////////////////////////////////////
        /// Sum quantity from POMistakeReturn
        ////////////////////////////////////////////////////////
        private int sumQuantityPOMistakeReturn(string orderno, string poid)
        {
            int ret = 0;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT SUM(Quantity) FROM [241_POMistakeReturn]"
                    + " WHERE POID='" + poid + "' AND OrderNo='" + orderno + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    if (!string.IsNullOrEmpty(dataReader[0].ToString()))
                    {
                        ret = Int32.Parse(dataReader[0].ToString());
                    }
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get sum quantity from POMistakeReturn for OrderNo " + orderno + " of POID " + poid);
            }
            return ret;
        }

        private void clearForm()
        {
            foreach (Control c in this.Controls)
            {
                if (c is DevExpress.XtraEditors.TextEdit)
                {
                    ((DevExpress.XtraEditors.TextEdit)c).Text = null;
                }

                if (c is DevExpress.XtraEditors.ComboBoxEdit)
                {
                    ((DevExpress.XtraEditors.ComboBoxEdit)c).SelectedIndex = -1;
                }

                if (c is System.Windows.Forms.MaskedTextBox)
                {
                    ((System.Windows.Forms.MaskedTextBox)c).Text = null;
                }
            }
        }
    }
}
